package com.apps.diet.endpoint;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.apps.diet.domain.Meals;
import com.apps.diet.oxm.EditMealsRequest;
import com.apps.diet.oxm.EditMealsResponse;
import com.apps.diet.service.MealsService;


/**
 * Handles meals requests. 
 * <p>
 *<pre>
 * @Endpoint: similar to Spring MVC's @Controller. 
 * @PayloadRoot: similar to Spring MVC's @RequestMapping</pre>
 */
@Endpoint
public class EditMealsEndpoint {

	protected static Logger logger = Logger.getLogger(EditMealsEndpoint.class);

	@Resource(name="mealsService")
	private MealsService mealsService;
	
	public static final String NAMESPACE_URI = "http://diet.apps.com/ws/schema/diet";

	public static final String REQUEST_LOCAL_NAME = "editMealsRequest";

	@PayloadRoot(localPart = REQUEST_LOCAL_NAME, namespace = NAMESPACE_URI)
	@ResponsePayload
	public EditMealsResponse editMeals( @RequestPayload EditMealsRequest editMealsRequest) {
		try {
			String editType = editMealsRequest.getEditType();
			Meals meals = editMealsRequest.getMeals();
			if (editType.equals("ADD")){
				logger.debug("Add operation");
				mealsService.createMeals(meals);				
			}else{
				logger.debug("Edit operation");
				mealsService.updateMeals(meals);
			}
		}  catch (Exception e) {
			logger.error("Unable to save meals");
			EditMealsResponse response = new EditMealsResponse();
			response.setCode("FAILURE");
			return response;
		}
		
		EditMealsResponse response = new EditMealsResponse();
		response.setCode("SUCCESS");

		return response;
	}
}
